package com.edais.service.imp;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.edais.dao.AgreementTemplateDao;
import com.edais.dao.AssignRuleDao;
import com.edais.dao.LoanDao;
import com.edais.dao.RateRisesCouponsDao;
import com.edais.dao.UserChannelPointDao;
import com.edais.domain.AssignRule;
import com.edais.domain.RateRisesCoupons;
import com.edais.domain.RiskEvaluation;
import com.edais.domain.UserChannelPoint;
import com.edais.service.OrderService;
import com.edais.service.RiskEvaluationService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.DateUtil;
import com.edais.util.DecimalFormatUtil;
import com.edais.util.Message;
import com.edais.vo.CreditDetailVo;
import com.edais.vo.OrderListVo;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class OrderServiceImp implements OrderService {
	private static final Log logger = LogFactory.getLog(OrderServiceImp.class);
	
	@Autowired
	private RateRisesCouponsDao rateRisesCouponsDao;
	
	@Autowired
	private UserChannelPointDao userChannelPointDao;
	
	@Autowired
	private AssignRuleDao assignRuleDao;
	@Autowired
	private AgreementTemplateDao agreementTemplateDao;
	@Autowired
	private RiskEvaluationService riskEvaluationService;
	
	@Autowired
	private LoanDao loanDao;
	/**
	 * 查询订单列表（暂进行中，已完成）
	 */
	@Override
	public String getOrdeInfoList(Map<String, Object> map)  throws Exception{
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		List<OrderListVo> ordersVoList = new ArrayList<OrderListVo>();
		
		String transCode = "E320007";
		Map<String,Object> coreMap = new HashMap<String,Object>();
		coreMap.put("type", map.get("type"));
		coreMap.put("userId", map.get("userId"));
		coreMap.put("pageSize", map.get("pageSize"));
		
		coreMap.put("current", map.get("currentPage"));
		
		coreMap.put("startDate", map.get("startDate") == null ? "" : map.get("startDate"));
		coreMap.put("endDate", map.get("endDate") == null ? "" : map.get("endDate"));
		coreMap.put("minInvestAmount", map.get("minInvestAmount") == null ? "" : map.get("minInvestAmount"));
		coreMap.put("productType", map.get("productType") == null ? "" : map.get("productType"));
		coreMap.put("remanPeriods", map.get("remanPeriods") == null ? "" : map.get("remanPeriods"));
		coreMap.put("notInOrder", map.get("notInOrder") == null ? "" : map.get("notInOrder"));
		coreMap.put("isAddOverFlg", map.get("isAddOverFlg") == null ? "" : map.get("isAddOverFlg"));
		coreMap.put("remanDays", map.get("remanDays") == null ? "" : map.get("remanDays"));
		coreMap.put("mobile", map.get("mobile") == null ? "" : map.get("mobile"));
//		coreMap.put("mobilekcodeSign", map.get("mobilekcodeSign") == null ? null : map.get("mobilekcodeSign"));
		// 构建json字符串
		String jsonStr = CommonUtil.constructJsonStr(transCode, null, coreMap);
		// 调用核心接口
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);
		
		// rescode = "00000"
		if(Consts.SUCCESS_CODE.equals(jsonObject.getString("rescode"))){
			JSONArray jsonArr = jsonObject.getJSONArray("list");
			if(jsonArr != null && jsonArr.size() > 0){
				for(int i = 0; i < jsonArr.size(); i++){
					JSONObject jsonObj = jsonArr.getJSONObject(i);
					OrderListVo orderVo = new OrderListVo();
					orderVo.setOrderId(jsonObj.getString("orderId"));//投资序号
					orderVo.setProductName(jsonObj.getString("productName"));//产品名称
					orderVo.setBorrowType(jsonObj.getString("borrowType"));//借款用途
					orderVo.setOrderValue(jsonObj.getString("orderValue"));//资产价值
					orderVo.setEarnInterest(jsonObj.getString("earnInterest"));//累计赚取金额
					orderVo.setInvestDate(jsonObj.getString("investDate"));//加入时间
					orderVo.setEndTime(jsonObj.getString("endTime"));//债权到期日
					
					orderVo.setOrderStatus(jsonObj.getString("orderStatus")); //订单状态
					
					orderVo.setDisposeState(jsonObj.getString("disposeState"));//投资状态
					orderVo.setInvestAmount(jsonObj.getString("investAmount"));//投资金额
					orderVo.setAnnualRate(jsonObj.getString("annualRate")); //年利率
					orderVo.setSloanId(jsonObj.getString("sloanId"));//上架表id
					orderVo.setOrderState(jsonObj.getString("orderState"));//订单状态
					orderVo.setInvestLimit(String.valueOf(CommonUtil.daysBetween(jsonObj.getString("investDate"), jsonObj.getString("endTime"))));
					orderVo.setAssignmentStatus(jsonObj.getString("assignmentStatus"));
					orderVo.setAssignUserType(jsonObj.getString("assignUserType"));
					
					//查询订单加息信息
					map.put("orderId", orderVo.getOrderId());
					map.put("status", "1");
					map.put("productId","108");
//					map.put("useFlag", "1");
					BigDecimal rateRises = BigDecimal.ZERO;
					List<RateRisesCoupons> useCouponsList = this.rateRisesCouponsDao.getRateRisesCouponsListByOrderId(map);
					for(RateRisesCoupons coupons:useCouponsList){
						rateRises = rateRises.add(coupons.getRate_rises());
					}

					orderVo.setCouponsRateRises(setFormatMoney1(String.valueOf(rateRises), 1));
//					orderVo.setCouponsRateRises(df.format(rateRises));
					//调整利率
					orderVo.setAdjustRate(jsonObj.getString("adjustRate"));
					
					String orderStatus=jsonObj.getString("orderStatus");
					if("1".equals(orderStatus)  || "5".equals(orderStatus)){
						//orderVo.setCouponsRateRises(couponsRateRises);
						//专享利率adjustRate  基础利率annualRate。    couponsRateRises 加息券
						// 获取债券转让规则数据
						Map<String,Object> ruleMap = new HashMap<String, Object>();
						ruleMap.put("userType", jsonObj.getString("assignUserType"));
						//根据投资日期算起息日
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
						Date startDate = format.parse(jsonObj.getString("investDate"));
						Calendar cal = Calendar.getInstance();
						cal.setTime(startDate);
						cal.add(Calendar.DATE, 1);
						String startDateStr = format.format(cal.getTime());
						ruleMap.put("startDate", startDateStr);
						ruleMap.put("assignApplyDate", format.format(new Date()));
						logger.info("客户种类："+jsonObj.getString("assignUserType"));
						logger.info("起息日："+startDateStr);
						List<AssignRule> ruleList = assignRuleDao.getAssignRuleList(ruleMap);
						if (ruleList != null && ruleList.size() > 0) {
							AssignRule rule = ruleList.get(0);
							if (rule != null) {
								logger.info("配置加息利率："+rule.getCouponsRate());
								logger.info("配置基准利率："+rule.getAnnualRate());
								orderVo.setCouponsRateRises(setFormatMoney1(String.valueOf(rule.getCouponsRate().multiply(new BigDecimal(100))),1));
								orderVo.setAnnualRate(setFormatMoney1(String.valueOf(rule.getAnnualRate().multiply(new BigDecimal(100))),1));
							}
						}
					}
					
					ordersVoList.add(orderVo);
				}
				rtnMap.put("totalNum", jsonObject.getString("totalNum"));
				rtnMap.put("listSize", ordersVoList.size());
				rtnMap.put("list", ordersVoList);
			}else{
				rtnMap.put("totalNum", 0);
				rtnMap.put("listSize", 0);
				rtnMap.put("list", new ArrayList()); 
			}
			// 设置返回code
			return CommonUtil.setResultStringCn(rtnMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,"");
		}else {
			logger.debug("=====核心接口E320007调用异常=====");
			logger.debug("rescode：" + jsonObject.getString("rescode") + "；  resmsg：" + jsonObject.getString("resmsg"));
			return CommonUtil.setResultStringCn(rtnMap, Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
		}
	}
	
	/**债权详情*/
	@Override
	public String getCreditInfoList(Map<String, Object> map) throws Exception {
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		List<CreditDetailVo> creditDetailVoList = new ArrayList<CreditDetailVo>();
		
		String transCode = "E320008";
		Map<String,Object> coreMap = new HashMap<String,Object>();
		coreMap.put("orderId", map.get("orderId"));
		
		// 构建json字符串
		String jsonStr = CommonUtil.constructJsonStr(transCode, null, coreMap);
		// 调用核心接口
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);
		
		// rescode = "00000"
		if(Consts.SUCCESS_CODE.equals(jsonObject.getString("rescode"))){
			JSONArray jsonArr = jsonObject.getJSONArray("list");
			if(jsonArr != null && jsonArr.size() > 0){
				for(int i = 0; i < jsonArr.size(); i++){
					JSONObject jsonObj = jsonArr.getJSONObject(i);
					CreditDetailVo creditDetailVo = new CreditDetailVo();
					creditDetailVo.setBidName(jsonObj.getString("bidName"));//借款用途
					creditDetailVo.setResidualPeriods(jsonObj.getString("residualPeriods"));//剩余期数
					creditDetailVo.setLoanPeriods(jsonObj.getString("loanPeriods"));//借款期限
					creditDetailVo.setInterestRate(jsonObj.getString("interestRate"));//年化利率
					creditDetailVo.setCreditAmount(jsonObj.getString("creditAmount"));//出借金额
					creditDetailVo.setIncomeInterest(jsonObj.getString("incomeInterest"));//已回收利息
					creditDetailVo.setIncomePrincipal(jsonObj.getString("incomePrincipal"));//已回收本金
					creditDetailVo.setEndDate(jsonObj.getString("endDate"));//债权到期日
					creditDetailVo.setTradeState(jsonObj.getString("tradeState"));//状态
					creditDetailVo.setCreditAcctCid(jsonObj.getString("creditAcctCid"));//债权编号
					creditDetailVo.setInvestorId(jsonObj.getString("investorId"));//理财人ID（用户ID）
					
					creditDetailVoList.add(creditDetailVo);
				}
				rtnMap.put("totalNum", jsonObject.getString("totalNum"));
				rtnMap.put("listSize", creditDetailVoList.size());
				rtnMap.put("list", creditDetailVoList);
			}else{
				rtnMap.put("totalNum", 0);
				rtnMap.put("listSize", 0);
				rtnMap.put("list", new ArrayList()); 
			}
			// 设置返回code
			return CommonUtil.setResultStringCn(rtnMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,"");
		}else {
			logger.debug("=====核心接口E320008调用异常=====");
			logger.debug("rescode：" + jsonObject.getString("rescode") + "；  resmsg：" + jsonObject.getString("resmsg"));
			return CommonUtil.setResultStringCn(rtnMap, Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
		}
	}

	/**
	 * 
	 * @Description: 根据订单id查询订单信息
	 * @param map
	 * @return
	 * @throws Exception   
	 * @return String  
	 * @throws
	 * @author qibo
	 * @date 2015-9-4 下午3:54:54
	 */
	@Override
	public String getOrderFormDetails(Map<String, Object> map) throws Exception {
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		List<OrderListVo> ordersVoList = new ArrayList<OrderListVo>();
		Map<String, String> repTypeMap = new HashMap<String, String>();
		repTypeMap.put("AVERAGE_CAPITAL_PLUS_INTEREST", "等额本息");
		repTypeMap.put("PWRIOD_REPAYS_CAPTITAL", "先息后本");
		repTypeMap.put("AVERAGE_CAPITAL_PRINCIPAL", "等额本金");
		repTypeMap.put("MATURITY_DEBT", "到期还本付息");
		
		String transCode = "E320009";
		Map<String,Object> coreMap = new HashMap<String,Object>();
		coreMap.put("orderId", map.get("orderId"));
		coreMap.put("loanId", map.get("loanId"));
		
		// 构建json字符串
		String jsonStr = CommonUtil.constructJsonStr(transCode, null, coreMap);
		// 调用核心接口
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);
		
		// rescode = "00000"
		if(Consts.SUCCESS_CODE.equals(jsonObject.getString("rescode"))){
			JSONArray jsonArr = jsonObject.getJSONArray("list");
			if(jsonArr != null && jsonArr.size() > 0){

				BigDecimal adjustRate = BigDecimal.ZERO;
				UserChannelPoint userChannelPoint = null;
				// 有订单的时候 直接拿订单内的调整利率
				if (map.get("orderId") == null || "".equals(map.get("orderId"))) {
					if (map.get("userId") != null && !"".equals(map.get("userId"))) {
						Map<String,Object> parm = new HashMap<String, Object>();
						parm.put("userId", map.get("userId"));
						userChannelPoint = userChannelPointDao.findChannelPointByParm(parm);
					}
				}

				for(int i = 0; i < jsonArr.size(); i++){
					JSONObject jsonObj = jsonArr.getJSONObject(i);
					OrderListVo orderVo = new OrderListVo();
					orderVo.setOrderId(jsonObj.getString("orderId"));//投资序号
					orderVo.setProductName(jsonObj.getString("productName"));//产品名称
					orderVo.setBorrowType(jsonObj.getString("borrowType"));//借款用途
					orderVo.setOrderValue(jsonObj.getString("orderValue"));//资产价值
					orderVo.setEarnInterest(jsonObj.getString("earnInterest"));//累计赚取金额
					orderVo.setInvestDate(jsonObj.getString("investDate"));//加入时间
					orderVo.setEndTime(jsonObj.getString("endTime"));//债权到期日
					
					orderVo.setAssignApplyDate(jsonObj.getString("assignApplyDate"));//债权转让申请日期
					orderVo.setAuditTime(jsonObj.getString("auditTime"));//债权转让审核日期
					orderVo.setOrderStatus(jsonObj.getString("orderStatus")); //订单状态
					
					orderVo.setDisposeState(jsonObj.getString("disposeState"));//投资状态
					orderVo.setInvestAmount(jsonObj.getString("investAmount"));//投资金额
					orderVo.setAnnualRate(jsonObj.getString("annualRate")); //年利率
					orderVo.setStartDate(jsonObj.getString("startDate")); //起息日期
					
					orderVo.setAssignFee(jsonObj.getString("assignFee")); //债权转让手续费
					orderVo.setOrderCancelDate(jsonObj.getString("orderCancelDate")); //订单取消日期
					orderVo.setApplyStatus(jsonObj.getString("applyStatus"));//债权转让申请状态
					orderVo.setAssignCompleteDate(jsonObj.getString("assignCompleteDate")); //债权转让完成日期
					
					orderVo.setInvestPeriod(jsonObj.getString("investPeriod")); //投资期限
					orderVo.setRemanDays(jsonObj.getString("remanDays")); //投资天数
					
					
					/**
					 * [新增]  债权转让还款方式 
					 * orderStatus订单状态(1.已转让，2.已完成，3.已取消，4.回款中，5.转让中，6.可转让)
					 */
					String orderStatus = orderVo.getOrderStatus();
					if("1".equals(orderStatus) || "5".equals(orderStatus) || "6".equals(orderStatus)){
						orderVo.setRepaymentType("到期还本付息,可提前退出"); //[新增]  债权转让还款方式 
					}else{
						
						orderVo.setRepaymentType(repTypeMap.get(jsonObj.getString("repaymentType"))); //还款方式
					}
										
					orderVo.setExpectedReturn(jsonObj.getString("expectedReturn")); //预期收益
					orderVo.setSloanId(jsonObj.getString("sloanId")); //上架表id
					orderVo.setInvestMinAmount(jsonObj.getString("investMinAmount")); //起投金额
					orderVo.setRemanAmount(jsonObj.getString("remanAmount")); //剩余金额
					orderVo.setContactAmount(jsonObj.getString("contactAmount")); //借款总额
					orderVo.setExpectedReturnDays(jsonObj.getString("expectedReturnDays"));//收益天数
					orderVo.setUserId(jsonObj.getString("userId"));//用户id
					orderVo.setOrderState(jsonObj.getString("orderState"));
					orderVo.setRateRises(jsonObj.getString("rateRises"));
//					orderVo.setInvestLimit(String.valueOf(CommonUtil.daysBetween(jsonObj.getString("investDate"), jsonObj.getString("endTime"))));
					
					//债权转让
					String assignmentStatus = jsonObj.getString("assignmentStatus");
					String assignUserType = jsonObj.getString("assignUserType");
					
					
					
					SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
					Date startDate = format.parse(jsonObj.getString("startDate"));
					Calendar cal = Calendar.getInstance();
					cal.setTime(startDate);
					cal.add(Calendar.MONTH, 3);
					String assignDate = format.format(cal.getTime());
					orderVo.setAssignDate(assignDate); //债权可转让日期
					
					Date systemDate = format.parse(jsonObj.getString("systemDate"));
					//当前数据库系统时间与起息日相差月数
					int months = DateUtil.getMonths(systemDate, startDate);
					if(months < 3){
						orderVo.setIsAssign("N");
					}else if(months > 12){
						orderVo.setIsAssign("N");
					}else{
						orderVo.setIsAssign("Y");
					}
					//给前端APP展现用
					//DecimalFormat df = new DecimalFormat("0.0");
					orderVo.setCouponsRateRises(setFormatMoney1((String)map.get("couponsRateRises"),1));
					orderVo.setAnnualInterest(jsonObj.getString("annualInterest"));//实际收益
					
					//ouyy 如果是这三种状态，加息利率和基准利率应该是超享计划债权转让的利率
					if("1".equals(orderStatus)  || "5".equals(orderStatus)){
						//orderVo.setCouponsRateRises(couponsRateRises);
						//专享利率adjustRate  基础利率annualRate。    couponsRateRises 加息券
						// 获取债券转让规则数据
						Map<String,Object> ruleMap = new HashMap<String, Object>();
						ruleMap.put("userType", assignUserType);
						ruleMap.put("startDate", jsonObj.getString("startDate"));
						ruleMap.put("assignApplyDate", jsonObj.getString("assignApplyDate"));
						logger.info("客户种类："+assignUserType);
						logger.info("起息日："+jsonObj.getString("startDate"));
						logger.info("债权转让申请日期："+jsonObj.getString("assignApplyDate"));
						List<AssignRule> ruleList = assignRuleDao.getAssignRuleList(ruleMap);
						if (ruleList != null && ruleList.size() > 0) {
							AssignRule rule = ruleList.get(0);
							if (rule != null) {
								logger.info("配置加息利率："+rule.getCouponsRate());
								logger.info("配置基准利率："+rule.getAnnualRate());
								orderVo.setCouponsRateRises(setFormatMoney1(String.valueOf(rule.getCouponsRate().multiply(new BigDecimal(100))),1));
								orderVo.setAnnualRate(setFormatMoney1(String.valueOf(rule.getAnnualRate().multiply(new BigDecimal(100))),1));
								//计算期数
								SimpleDateFormat smdf = new SimpleDateFormat("yyyy-MM-dd");
								Date start = smdf.parse(jsonObj.getString("startDate"));
								Date end = smdf.parse(smdf.format(new Date()));
								long t = ((end.getTime() - start.getTime()) / (3600 * 24 * 1000))+1;
								logger.info("计息天数："+ t);
								BigDecimal b1=new BigDecimal(jsonObj.getString("investAmount"));//本金
								BigDecimal b2=rule.getCouponsRate(); //加息利率
								BigDecimal b3=b2.add(rule.getAnnualRate());//加息利率+基准利率
								BigDecimal b4=b1.multiply(b3).multiply(new BigDecimal(t)).divide(new BigDecimal(365),6);
								logger.info("计算后的利率："+ b1+"||"+ b2+"||"+ b3+"||"+b4);
								orderVo.setExpectedReturn(CommonUtil.setFormatMoney(String.valueOf(b4)));
							}
						}
					}
					
					orderVo.setAssignmentStatus(assignmentStatus);
					orderVo.setAssignUserType(assignUserType);

					// 有订单的时候 直接拿订单内的调整利率
					if (map.get("orderId") == null || "".equals(map.get("orderId"))) {
						if (userChannelPoint != null) {
							if ("Y".equals(jsonObj.getString("isAdjustRate"))) {
								adjustRate = new BigDecimal(jsonObj.getString("maxAdjustRate")).multiply(
										new BigDecimal(userChannelPoint.getFixFloatRateChannel()));
							}
						}
					} else {
						adjustRate = new BigDecimal(jsonObj.getString("adjustRate"));
					}
					
					//调整利率
					orderVo.setAdjustRate(adjustRate.setScale(1, RoundingMode.DOWN).toString());
					orderVo.setMaxAdjustRate(jsonObj.getString("maxAdjustRate"));
					orderVo.setIsAdjustRate(jsonObj.getString("isAdjustRate"));
					orderVo.setAgreementAutoid(jsonObj.getString("agreementAutoid"));
					orderVo.setAgreementNo(jsonObj.getString("agreementNo"));
					orderVo.setAssetNo(jsonObj.getString("assetNo"));
					
					try {//gaojing 风险评估
						RiskEvaluation riskEvaluation=riskEvaluationService.getRiskEvaluationByUserId((String)map.get("userId"));
						orderVo.setIsRiskEvaluation(riskEvaluation.getIsRisk());
						orderVo.setRiskType(riskEvaluation.getRiskType());
					} catch (Exception e) {
						logger.error("查询风险评估异常",e);
						orderVo.setIsRiskEvaluation("N");
						orderVo.setRiskType("未评估");
					}
					//gaojing 查询购买进度
					try {
						String finishedRatio=loanDao.getFinishedRatio(orderVo.getSloanId());
						BigDecimal bigFinishedRatio = DecimalFormatUtil.getDecimalFormat0(BigDecimal.ONE.compareTo(new BigDecimal(finishedRatio))>0 
								&& BigDecimal.ZERO.compareTo(new BigDecimal(finishedRatio))<0?BigDecimal.ONE:new BigDecimal(finishedRatio));
						orderVo.setFinishedRatio(bigFinishedRatio);
					
					} catch (Exception e) {
						orderVo.setFinishedRatio(new BigDecimal(0));
						logger.error("查询购买进度异常！",e);
					}
					
					ordersVoList.add(orderVo);
							
				}
				rtnMap.put("list", ordersVoList);
			}else{
				rtnMap.put("list", new ArrayList()); 
			}
	
			// 设置返回code
			return CommonUtil.setResultStringCn(rtnMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,"");
		}else {
			logger.debug("=====核心接口E320009调用异常=====");
			logger.debug("rescode：" + jsonObject.getString("rescode") + "；  resmsg：" + jsonObject.getString("resmsg"));
			return CommonUtil.setResultStringCn(rtnMap, Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
		}
	}
	
	/**
	 * ouyy
	 * 设置金额格式
	 * @param context 金额
	 * @return
	 */
	private  String setFormatMoney1(String context,int flag) {
		if(context==null||"".equals(context.trim()) || "null".equals(context)){
			return "0";
		}
		StringBuffer sb=new StringBuffer();
		if(context.lastIndexOf(".")!=-1){
			String pdly=context.substring(context.lastIndexOf(".")+1);
			if(pdly!=null&&!"".equals(pdly.trim())){
				if(pdly!=null&&pdly.length()==1){
					if(flag==2){
						if("0".equals(pdly)){
							pdly=context.substring(0,context.lastIndexOf("."));
							sb.append(pdly);
						}else{
							sb.append(context);
						}	
					}else{
						//订单列表 加息券数值调整为需保留一位小数
						pdly=context.substring(0,context.lastIndexOf("."))+"." + pdly ;
//						pdly=context.substring(0,context.lastIndexOf("."))+".0";
						sb.append(pdly);
					}
									
				}else if(pdly.length()==2){
					if("00".equals(pdly)){
						pdly=context.substring(0,context.lastIndexOf("."));
						sb.append(pdly);
					}else{
						sb.append(context);
					}	
				}else if(pdly.length()>=3){
					sb.append(pdly.substring(0,1));
				}
			}else{
				sb.append(context);
			}
			
		}else{
			if(flag==1){
				sb.append(context+".0");
			}else{
				sb.append(context);
			}
		}
		return sb.toString();
	}

	/**查询订单列表（返回LIST）*/
	@Override
	public List<OrderListVo> queryOrderList(Map<String, Object> map)
			throws Exception {
		List<OrderListVo> ordersVoList = new ArrayList<OrderListVo>();
		
		String transCode = "E320007";
		Map<String,Object> coreMap = new HashMap<String,Object>();
		coreMap.put("type", map.get("type"));
		coreMap.put("userId", map.get("userId"));
		coreMap.put("pageSize", map.get("pageSize"));
		coreMap.put("current", map.get("currentPage"));
		
		coreMap.put("notInOrder", map.get("notInOrder") == null ? "" : map.get("notInOrder"));
		coreMap.put("productType", map.get("productType") == null ? "" : map.get("productType"));
		coreMap.put("isAddOverFlg", map.get("isAddOverFlg") == null ? "" : map.get("isAddOverFlg"));
		// 构建json字符串
		String jsonStr = CommonUtil.constructJsonStr(transCode, null, coreMap);
		// 调用核心接口
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);
		
		// rescode = "00000"
		if(Consts.SUCCESS_CODE.equals(jsonObject.getString("rescode"))){
			JSONArray jsonArr = jsonObject.getJSONArray("list");
			if(jsonArr != null && jsonArr.size() > 0){
				for(int i = 0; i < jsonArr.size(); i++){
					JSONObject jsonObj = jsonArr.getJSONObject(i);
					OrderListVo orderVo = new OrderListVo();
					orderVo.setOrderId(jsonObj.getString("orderId"));//投资序号
					orderVo.setProductName(jsonObj.getString("productName"));//产品名称
					orderVo.setBorrowType(jsonObj.getString("borrowType"));//借款用途
					orderVo.setOrderValue(jsonObj.getString("orderValue"));//资产价值
					orderVo.setEarnInterest(jsonObj.getString("earnInterest"));//累计赚取金额
					orderVo.setInvestDate(jsonObj.getString("investDate"));//加入时间
					orderVo.setEndTime(jsonObj.getString("endTime"));//债权到期日
					orderVo.setDisposeState(jsonObj.getString("disposeState"));//投资状态
					orderVo.setInvestAmount(jsonObj.getString("investAmount"));//投资金额
					orderVo.setAnnualRate(jsonObj.getString("annualRate")); //年利率
					orderVo.setSloanId(jsonObj.getString("sloanId"));//上架表id
					orderVo.setOrderState(jsonObj.getString("orderState"));//订单状态
					orderVo.setInvestLimit(String.valueOf(CommonUtil.daysBetween(jsonObj.getString("investDate"), jsonObj.getString("endTime"))));
					
					//查询订单加息信息
					map.put("orderId", orderVo.getOrderId());
					map.put("status", "1");
					map.put("productId","108");
	//							map.put("useFlag", "1");
					BigDecimal rateRises = BigDecimal.ZERO;
					List<RateRisesCoupons> useCouponsList = this.rateRisesCouponsDao.getRateRisesCouponsListByOrderId(map);
					for(RateRisesCoupons coupons:useCouponsList){
						rateRises = rateRises.add(coupons.getRate_rises());
					}
					orderVo.setCouponsRateRises(rateRises.toString());
					orderVo.setAssignmentStatus(jsonObj.getString("assignmentStatus"));
					orderVo.setAssignUserType(jsonObj.getString("assignUserType"));
					ordersVoList.add(orderVo);
				}
			}
		}
		return ordersVoList;
	}

	/* (non-Javadoc)
	 * @see com.edais.service.OrderService#getOrderInvestAmount(java.util.Map)
	 * 查询订单金额
	 */
	@Override
	public String getOrderInvestAmount(Map<String, String> map)
			throws Exception {
		// TODO Auto-generated method stub
		String transCode = "Q310001";//查询订单信息
		Map<String, Object> coreMap = new HashMap<String,Object>();
		coreMap.putAll(map);
		// 构建json字符串
		String jsonStr = CommonUtil.constructJsonStr(transCode, null, coreMap);
		// 调用核心接口
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);
		if(Consts.SUCCESS_CODE.equals(jsonObject.getString("rescode"))){
			if(jsonObject.containsKey("reponseMap")){
				JSONObject jsonObj= JSONObject.fromObject(jsonObject.getString("reponseMap"));
				if(jsonObj.containsKey("investAmount")){
					return jsonObj.getString("investAmount")==null?"0.00":jsonObj.getString("investAmount");
				}
			}
		}
		return "0.00";
	}
	/**
	 * 优享计划
	 */
	@Override
	public String getOrderInvestAmountForEnjoy(Map<String, String> map)
			throws Exception {
		// TODO Auto-generated method stub
		String transCode = "Q310001";//查询订单信息
		Map<String, Object> coreMap = new HashMap<String,Object>();
		coreMap.putAll(map);
		// 构建json字符串
		String jsonStr = CommonUtil.constructJsonStr(transCode, null, coreMap);
		// 调用核心接口
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);
		if(Consts.SUCCESS_CODE.equals(jsonObject.getString("rescode"))){
			if(jsonObject.containsKey("reponseMap")){
				JSONObject jsonObj= JSONObject.fromObject(jsonObject.getString("reponseMap"));
				String enableAmountForEnjoy = "0.00";
				if(jsonObj.containsKey("frozenPreMatchFunds")){
					String frozenPreMatchFunds=jsonObj.getString("frozenPreMatchFunds")==null?"0.00":jsonObj.getString("frozenPreMatchFunds");
					enableAmountForEnjoy= String.valueOf(new BigDecimal(enableAmountForEnjoy).add(new BigDecimal(frozenPreMatchFunds)));
				}
				if(jsonObj.containsKey("frozenHasMatchFunds")){
					String frozenHasMatchFunds=jsonObj.getString("frozenHasMatchFunds")==null?"0.00":jsonObj.getString("frozenHasMatchFunds");
					enableAmountForEnjoy= String.valueOf(new BigDecimal(enableAmountForEnjoy).add(new BigDecimal(frozenHasMatchFunds)));
				}
				return enableAmountForEnjoy;
			}
		}
		return "0.00";
	}
	/** 
	 * 保存PDF文件路径到订单信息表中 */
	@Override
	public String savePDFPathOfOrder(Map<String, Object> map) throws Exception {
		String transCode = "E400002";//保存PDF文件路径
		Map<String, Object> coreMap = new HashMap<String,Object>();
		coreMap.putAll(map);
		String jsonStr = CommonUtil.constructJsonStr(transCode, null, coreMap);// 构建json字符串
		String rtnStr = CommonUtil.getCoreValue(jsonStr);// 调用核心接口
		return rtnStr;
	}
	/**
	 * @author gongyl
	 * @Description:下载合同-根据pdf文件路径下载用户的合同 ， E400003=getPDFPathAction
	 * @param map
	 * @return：map
	 * @throws Exception 
	 * @time:2016年12月09日
	 */
	@Override
	public String getPDFPathByOrderId(Map<String, Object> map) throws Exception {
		String transCode = "E400003";//获取pdf文件路径
		Map<String, Object> coreMap = new HashMap<String,Object>();
		coreMap.putAll(map);
		String jsonStr = CommonUtil.constructJsonStr(transCode, null, coreMap);// 构建json字符串
		String rtnStr = CommonUtil.getCoreValue(jsonStr);// 调用核心接口
		return rtnStr;
	}
	/**
	 * 印章订单列表管理
	 * @date 2016-12-22
	 * @author gongyl
	 * @throws Exception
	 */
	@Override
	public String getOrderList4Seal(Map<String, Object> map) throws Exception {
		String transCode = "E400004";
		Map<String, Object> coreMap = new HashMap<String,Object>();
		coreMap.putAll(map);
		String jsonStr = CommonUtil.constructJsonStr(transCode, null, coreMap);// 构建json字符串
		String rtnStr = CommonUtil.getCoreValue(jsonStr);// 调用核心接口
		return rtnStr;
	}
	/**
	 * 盖章按钮
	 * @date 2016-12-22
	 * @author gongyl
	 * @throws Exception
	 */
	@Override
	public void doSeal(Map<String, Object> paramsMap) throws Exception {
		 agreementTemplateDao.doSeal(paramsMap);
	}

	
	/**
	 * 查询定期3月期、6月期和发现的订单详情
	 */
	@Override
	public Map<String, Object> queryCusOrderList(String logInfo, Map<String, Object> params)throws Exception{
		Map<String, Object> map = new HashMap<String, Object>();
		
		Map coreMap = CommonUtil.invokeCore(logInfo, "cusOrderService", params);
		if (coreMap == null || !"00000".equals(coreMap.get("rescode"))) {
			logger.error(logInfo + "查询订单信息失败：" + coreMap.get("resmsg"));
			map.put("rescode", Consts.ERROR_CODE);
			map.put("resmsg", Consts.ErrorMsg.MSG00001);
			map.put("resmsg_cn", "查询订单信息失败");
			return map;
		}

		return coreMap;
	}
	
}
